package com.calligraphy.product.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.calligraphy.bases.utils.SetMsg;
import com.calligraphy.product.exception.ProductException;
import com.calligraphy.product.form.CategoryForm;
import com.calligraphy.product.model.ProductCategory;
import com.calligraphy.product.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 类目
 * @Author hy
 * @Date 2019/1/11 10:29
 **/
@Slf4j
@RestController
@RequestMapping("/seller/category")
public class SellerCategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 保存/更新
     * @param form
     * @param bindingResult
     * @return
     */
    @PostMapping("/save")
    public JSONObject save(@Validated CategoryForm form,
                           BindingResult bindingResult){
        JSONObject json = new JSONObject();
        if(bindingResult.hasErrors()){
            json.put("msg",bindingResult.getFieldError().getDefaultMessage());
            SetMsg.setMessage(json,1,"false");
            return json;
        }
        ProductCategory productCategory=new ProductCategory();
        try {
            if(form.getCategoryId()!=null){
                productCategory=categoryService.findOne(form.getCategoryId());
            }
            BeanUtils.copyProperties(form,productCategory);
            categoryService.save(productCategory);
        }catch (ProductException e){
            json.put("msg",e.getMessage());
            SetMsg.setMessage(json,1,"false");
            return json;
        }
        SetMsg.setMessage(json,0,"success");
        return json;

    }

    @GetMapping("/list")
    public JSONObject list(){
        JSONObject json = new JSONObject();
        List<ProductCategory> categoryList=categoryService.findAll();
        json.put("categoryList",categoryList);
        SetMsg.setMessage(json,0,"success");
        return json;
    }



}
